<?php
/* Copyright [2014] UW-Parkside
 * Authors: Matthew Zygowicz, Armando Narvaez
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

/**
 *This model controls the logic involved with manipulating Routes
 *and the routetable table.  Any operation involving a route should
 *be done in this class.
 */
class Routes extends CI_Model {

    /**
     *Load the database from the config file, and register this function
     *as a valid codeigniter model
     */
    public function __construct() {
        $this->load->database();
        parent::__construct();
    }

    /**
     *This function retrives all of the routes and directions from the table
     *
     *@return array returns an array of the format array(route=>data, direction=>data)
     */
    public function getAllRoutes() {
        //this function will return an array of all possible routes with directons and a direction for all
        $sql = "SELECT route, direction FROM routetable GROUP BY route, direction;";
        $query = $this->db->query($sql);
        
        $currentRoute = '';
        $resultArray = array();
        //build friendly array
        foreach($query->result_array() as $result){
            if($currentRoute != $result['route']){
                $resultArray[] = array('route' => $result['route'], 'direction' => 'All');
                $currentRoute = $result['route'];
            }
            $resultArray[] = $result;
        }
        return $resultArray;
    }
    
    /**
     *This function returns the current max _id from the table
     *
     *@return array returns an array of 1 element with the max id
     */
    public function getNumberOfRows() {
        $sql = "SELECT MAX(_id) FROM `routetable`;";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    /**
     *This function gets routeData from the database given the parameters
     *
     *@param int $routeKey the routeNumber wanting to be returned
     *@param string $direction the optional direction for the given $routeKey
     */
    public function getRouteData($routeKey, $direction=NULL) {
        //this function will return an array of all stops for a given route
        if(isset($direction) && strtoupper($direction) != "ALL")
            $sql = "SELECT location, day, time, _id, direction FROM routetable where route = $routeKey AND direction='$direction' ORDER BY time;";
        else
            $sql = "SELECT direction, location, day, time, _id FROM routetable where route = $routeKey ORDER BY time;";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    /**
     *This function will update a any given route id's location,day,time or direction
     *
     *@param int $id the routetable id of the specific record wanting to be editted
     *@param string $location the string that will become this records location
     *@param string $day the string that will become this records day
     *@param string $time the string that will become this records time
     *@param string $direction the string that will become this records direction
     */
    public function editRoute($id, $location, $day, $time, $direction) {
        $sql = "UPDATE routetable SET location=?, day=?, time=?, direction=? WHERE _id=?;";
        $query = $this->db->query($sql, array($location, $day, $time, $direction, $id));
        $this->writeLogFile($id, 'update');
        $this->insert_route_version();
    }

    /**
     *This function handles the logic involved with adding a route given the parameters
     *
     *@param int $id the routetable id of the specific record wanting to be created
     *@param string $location the string that will become this records location
     *@param string $day the string that will become this records day
     *@param string $time the string that will become this records time
     *@param string $direction the string that will become this records direction
     */
    public function addRoute($routeNumber, $location, $day, $time, $direction) {
        $sql = "INSERT INTO routetable (`route`, `location`, `day`, `time`, `direction`) VALUES(?,?,?,?,?);";
        $query = $this->db->query($sql, array($routeNumber, $location, $day, $time, $direction));
        $this->insert_route_version();
        //$this->writeLogFile($id, 'insert');
    }

    /**
     *This function checks whether or not a given routeNumber already exists
     *within the table
     *
     *@param int $routeNumber the routeNumber to be checked
     *@return boolean returns true if the routeNumber already exists
     *@return boolean returns false if the routeNumber does not exist
     */
    public function checkIfRouteExists($routeNumber) {
        $sql = "SELECT route FROM routetable WHERE route = ?;";
        $query = $this->db->query($sql, array($routeNumber));
        if ($query->num_rows() == 0) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     *Check if there is a duplicate entry, (This is used if the user refreshes the page)
     *
     *@param int $routeNumber the routeNumber to be checked
     *@param string $location the location of the routeNumber being checked
     *@param string $time the time of the routeNumber being checked
     *@return boolean returns true if the record already exists
     *@return boolean returns false if the record does not exist
     */
    public function checkIfRecordExists($routeNumber, $location, $time) {
        $sql = "SELECT route, location, time FROM routetable WHERE route = ? and location = ? and time = ?;";
        $query = $this->db->query($sql, array($routeNumber, $location, $time));
        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }

   /**
    *This function contains the logic involved with the deletion of entire routes.
    *
    *@param int $routeNumber the routeNumber to be deleted.
    */
    public function deleteRoute($routeNumber) {
        if (isset($_SESSION['user']) && $_SESSION['realm'] == 'Admin') {
            $sql = "Delete from routetable where route = '$routeNumber';";
            $query = $this->db->query($sql);
            $this->insert_route_version();
        }

    }

    /**
     *This function will delete a specific record of 
     *
     *@param int $routeId the record id of routetable to be deleted
     */
    public function deleteRouteRecord($routeId) {
        if (isset($_SESSION['user']) && $_SESSION['realm'] == 'Admin') {
            $sql = "Delete from routetable where _id = $routeId;";
            $query = $this->db->query($sql);
        }
        //writeLogFile($routeNumber, "delete"); //Write to File
    }

    /**
     *The following function takes a given file type and will dump the database
     *to that file type
     *Acceptable types are: xml, csv
     *returns true for success and false for failure
     *
     *@param string $filetype must be either 'xml' or 'csv'
     *@return boolean returns true if the file is successfully created
     *@return boolean returns false if the file is not created
     */
    public function create_file($fileType){
        $this->load->helper('file');
        $this->load->dbutil();
        $query = $this->db->query("SELECT * FROM routetable");
        
        switch($fileType){
            case 'xml':
                $data = $this->dbutil->xml_from_result($query);
                break;
            case 'csv':
                $data = $this->dbutil->csv_from_result($query);
                break;
            default:
                $data = 'error on filetype';
                break;
        }
        
       // var_dump($data);
        if ( ! write_file("./resources/data/routetable.$fileType", $data))
        {
             return false;
            //return $data;
        }
        else
        {
             
             return $this->_create_revision_file($fileType);
            // return $data;
        }
        
    }
    
    private function _create_revision_file($fileType){
        $this->load->helper('file');
        $this->load->dbutil();
        $query = $this->db->query("SELECT MAX(iRevision) 'version_number' FROM route_version");
        
        switch($fileType){
            case 'xml':
                $data = $this->dbutil->xml_from_result($query);
                break;
            case 'csv':
                $data = $this->dbutil->csv_from_result($query);
                break;
            default:
                $data = 'error on filetype';
                break;
        }
        
       // var_dump($data);
        if ( ! write_file("./resources/data/route_version.$fileType", $data))
        {
             return false;
            //return $data;
        }
        else
        {
             return true;
            // return $data;
        }
    }
    /**
     *This function inserts a new revision into the route_version
     *This function is to be called whenever a route is edited, deleted or added.
     */
    public function insert_route_version(){
         $sql = "INSERT INTO route_version (`iRevision`) VALUES(NULL);";
         $query = $this->db->query($sql);   
    }
    // Write to a log file when there's an update
    // Needs to be called when the button is clicked.
    public function writeLogFile($routeNumber, $option) {
        if (isset($_SESSION['user']) && $_SESSION['realm'] == 'admin') {
            $logFile = "logfile.txt"; //change to file name
            $open = fopen($logFile, 'w');

            /* Information to write to logfile */
            $user = $_SESSION['user'];
            $time = date();

            switch ($option) {
                case "update":
                    $data = "$user modified routes for $routeNumber at $time";
                    break;
                case "delete":
                    $data = "$user deleted route $routeNumber at $time";
                    break;
                case "insert":
                    $data = "$user inserted routes for $routeNumber at $time";
                    break;
            }


            fwrite($open, $data);
            fclose($open);
        }
    }

}

?>